package com.lenxia.spark.util

import java.sql.{Connection, PreparedStatement, ResultSet}

import org.apache.commons.dbcp.BasicDataSource


/**
  * Author  : Lenxia
  * Created : 2017/8/16
  * Updated : 2017/8/16
  * Version : 0.0.0
  * Contact : 2219708253@qq.com
  * 关系型数据库连接池
  */
object ConnectionPool {
  
  var datasource: BasicDataSource = null
  
  def initDataSource(): BasicDataSource = {
    
    if (datasource != null) {
      datasource = new BasicDataSource()
      datasource.setUsername("root")
      datasource.setPassword("root")
      datasource.setUrl("jdbc:mysql://localhost:3306/sparkStreaming")
      datasource.setDriverClassName("com.mysql.jdbc.Driver")
      datasource.setInitialSize(20)
      datasource.setMaxActive(100)
      datasource.setMinIdle(50)
      datasource.setMaxIdle(100)
      datasource.setMaxWait(1000)
      datasource.setMinEvictableIdleTimeMillis(5 * 60 * 1000)
      datasource.setTimeBetweenEvictionRunsMillis(10 * 60 * 1000)
      datasource.setTestOnBorrow(true)
    }
    datasource
  }
  
  def getConnection(): Connection = {
    var conn: Connection = null
    try {
      if (datasource != null) {
        conn = datasource.getConnection
      } else {
        conn = initDataSource().getConnection
      }
    } catch {
      case e: Exception => e.printStackTrace()
    }
    conn
  }
  
  def closeDataSource: Unit = if (datasource != null) {
    datasource.close()
  }
  
  def closeConnection(rs: ResultSet, ps: PreparedStatement, connect: Connection): Unit = {
    if (rs != null) {
      rs.close
    }
    if (ps != null) {
      ps.close
    }
    if (connect != null) {
      connect.close
    }
  }
}
